const User = require('../models/user');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { validationResult } = require('express-validator');

const userController = {
    async register(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { email, phone, full_name, username, password } = req.body;

        try {
            const existing = await User.findByEmail(email);
            if (existing) {
                return res.status(400).json({ error: 'Email already exists' });
            }

            const { user_id } = await User.create({ email, phone, full_name, username, password });

            const token = jwt.sign({ user_id }, process.env.JWT_SECRET, { expiresIn: '1h' });
            res.status(201).json({ token });
        } catch (error) {
            next(error);
        }
    },

    async login(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { email, password } = req.body;

        try {
            const user = await User.findByEmail(email);
            if (!user) {
                return res.status(400).json({ error: 'Invalid credentials' });
            }

            const isMatch = await bcrypt.compare(password, user.password_hash);
            if (!isMatch) {
                return res.status(400).json({ error: 'Invalid credentials' });
            }

            const token = jwt.sign({ user_id: user.user_id }, process.env.JWT_SECRET, { expiresIn: '1h' });
            res.json({ token });
        } catch (error) {
            next(error);
        }
    },

    async getProfile(req, res, next) {
        try {
            const user = await User.findById(req.params.user_id);
            if (!user) {
                return res.status(404).json({ error: 'User not found' });
            }
            res.json(user);
        } catch (error) {
            next(error);
        }
    },

    async updateProfile(req, res, next) {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        try {
            await User.update(req.user.user_id, req.body);
            res.json({ message: 'Profile updated successfully' });
        } catch (error) {
            next(error);
        }
    }
};

module.exports = userController;